import React from 'react';
import {Spin, Card, Button, Row, Col, Table, Form, Radio, Modal} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {FORM_OPTIONS, TABLE, DATE_FORMAT} from '../constants';
import {PERMISSION} from './constants';
import {hasPermissions, getUrl} from './utils';
import {injectIntl, language} from './intl';
import {formatAmount, conventEnumValueToString, formatDateTime} from '../utils';
import styles from './style.css';
import Return from '../common/Return';
import TextInput from 'Shared/components/TextInput';
import {partBackOrderStatus, currency, partBackOrderDealStatus} from '../Enum';
import WrappedSelect from '../common/WrappedSelect';
import DealerSelectPanel from '../common/DealerSelect/SelectEdit';
import LocalizeInputNumber from '../common/LocalizeInputNumber';
import TextArea from 'Shared/components/TextArea';
import {queryList} from './api';
const {confirm} = Modal;
const FormItem = Form.Item;
const partBackOrderStatusList = partBackOrderStatus.toList(language);
const partBackOrderDealStatusList = partBackOrderDealStatus.toList(language);
class ConfirmorPanel extends React.PureComponent {
    state = {
        id: '',
        dealerId: '',
        dealerCode: '',
        dealerName: '',
        brandId: '',
        partOrderCode: [],
        status: this.props.page === 'confirmor' ? partBackOrderStatus.新建 : partBackOrderStatus.已确认,
        dealStatus: this.props.page === 'confirmor' ? partBackOrderDealStatus.未处理 : undefined,
        loading: false,
        hasOperat: false,
        details: [],
        size: undefined,
        selectedRowKeys: [],
        selectedRows: [],
    }
    componentDidMount() {
        if(this.props.id) {
            const order = getUrl(this.props.history.location.search);
            this.setState({
                dealerId: order.dealerId,
                dealerName: order.dealerName,
                dealerCode: order.dealerCode,
                brandId: order.brandId,
                status: Number(order.status),
                partOrderCode: [order.code]
            });
            const condition = {
                id: this.props.id,
                status: this.state.status,
                dealStatus: this.state.dealStatus
            };
            this.onQuery(condition);
        } else {
            const condition = {
                status: this.state.status,
                dealStatus: this.state.dealStatus
            };
            this.onQuery(condition);
        }
    }
    componentWillUnmount() {
        this.isunmount = true;
    }
    dealStatusChange = (dealStatus, id) => {
        const details = this.state.details || [];
        const tmp = details.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    dealStatus
                });
            return d;
        });
        this.setState({
            details: tmp,
            hasOperat: true
        });
    }
    handleFilterPressEnter = (value, name) => {
        this.setState({[name]: value}, this.onClickSearchBtn);
    }

    onQuery = condition => {
        this.setState({loading: true});
        queryList(condition)
            .then(res => {
                if(res.ok)
                    this.setState({
                        loading: false,
                        message: '',
                        details: res.data.content.map(v => Object.assign({}, v, {
                            cancelQuantity: 0,
                            waitQuantity: 0,
                            transforQuantity: 0,
                        }))
                    });
                else
                    this.setState({
                        loading: false,
                        data: [],
                        message: res.message
                    });
            });
    }
    onChange = (value, name) => {
        this.setState({[name]: value});
    }
    onClickReset = () => {
        if(!this.props.id)
            this.setState({
                id: '',
                dealerId: '',
                dealerCode: '',
                dealerName: '',
                brandId: '',
                partOrderCode: [],
                status: undefined,
                dealStatus: undefined,
            });
    }
    onClickSearchBtn = () => {
        if(this.props.id) {
            const condition = {
                id: this.props.id,
                status: this.state.status,
                dealStatus: this.state.dealStatus
            };
            this.onQuery(condition);
        } else {
            const condition = {
                dealerId: this.state.dealerId,
                brandId: this.state.brandId,
                partOrderCode: this.state.partOrderCode,
                status: this.state.status,
                dealStatus: this.state.dealStatus
            };
            this.onQuery(condition);
        }
    }
    onClickOkOnPopconfirm = () => {
        this.props.onCancel();
    }
    onSubmit = () => {
        const {details} = this.state;
        if(details.some(v => v.dealStatus === partBackOrderDealStatus.未处理))
            this.onConfirmSubmit();
        else {
            this.setState({loading: true});
            this.props.onSubmit(details).then(res => {
                if(res.success)
                    this.props.successReturn();
                if(!this.isunmount)
                    this.setState({loading: false});
            });
        }
    }
    onConfirmSubmit = () => {
        const {details} = this.state;
        const thisData = this;
        confirm({
            title: this.props.intl.formatMessage({
                id: 'confirmorPanel.message.tips1',
                defaultMessage: '提示'
            }),
            content: this.props.intl.formatMessage({
                id: 'confirmorPanel.message.tips',
                defaultMessage: '有备件未处理，将默认作为继续等待,是否继续提交？'
            }),
            onOk() {
                thisData.setState({loading: true});
                thisData.props.onSubmit(details).then(res => {
                    if(res.success)
                        thisData.props.successReturn();
                    if(!thisData.isunmount)
                        thisData.setState({loading: false});
                });
            },
            okText: this.props.intl.formatMessage({
                id: 'confirmorPanel.message.okText',
                defaultMessage: '提交'
            }),
            cancelText: this.props.intl.formatMessage({
                id: 'confirmorPanel.message.cancelText',
                defaultMessage: '取消'
            }),
        });
    }
    onCloseSubmit = () => {
        const {dealerId, brandId, partOrderCode, status, dealStatus} = this.state;
        const {details} = this.state;
        if(details.some(v => v.waitQuantity > 0))
            this.onCloseSubmit1();
        else {
            this.setState({loading: true});
            this.props.onCloseSubmit({
                id: this.props.id,
                dealerId,
                brandId,
                partOrderCode,
                status,
                dealStatus
            }).then(res => {
                if(res.success)
                    this.props.successReturn();
                if(!this.isunmount)
                    this.setState({loading: false});
            });
        }
    }
    onCloseSubmit1 = () => {
        const thisData = this;
        const {dealerId, brandId, partOrderCode, status, dealStatus} = this.state;
        confirm({
            title: this.props.intl.formatMessage({
                id: 'confirmorPanel.message.tips1',
                defaultMessage: '提示'
            }),
            content: this.props.intl.formatMessage({
                id: 'confirmorPanel.message.tipsClose',
                defaultMessage: '存在继续等待的备件,是否继续提交？'
            }),
            onOk() {
                thisData.setState({loading: true});
                thisData.props.onCloseSubmit({
                    id: thisData.props.id,
                    dealerId,
                    brandId,
                    partOrderCode,
                    status,
                    dealStatus
                }).then(res => {
                    if(res.success)
                        thisData.props.successReturn();
                    if(!thisData.isunmount)
                        thisData.setState({loading: false});
                });
            },
            okText: this.props.intl.formatMessage({
                id: 'confirmorPanel.message.okText',
                defaultMessage: '提交'
            }),
            cancelText: this.props.intl.formatMessage({
                id: 'confirmorPanel.message.cancelText',
                defaultMessage: '取消'
            }),
        });
    }
    onSelectDealer = data => {
        this.setState({
            dealerId: data.id,
            dealerCode: data.code,
            dealerName: data.name,
        });
    }
    onChangeSize = e => {
        this.setState({
            size: e.target.value,
            hasOperat: true
        });
    }
    onUpdateQuantity = (cancelQuantity, id) => {
        const details = this.state.details || [];
        const selectedRows = this.state.selectedRows || [];
        const tmp = details.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    cancelQuantity,
                    waitQuantity: d.missQuantity - d.stockAmount - cancelQuantity
                });
            return d;
        });
        const tmpRows = selectedRows.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    cancelQuantity,
                    waitQuantity: d.missQuantity - d.stockAmount - cancelQuantity
                });
            return d;
        });
        this.setState({
            details: tmp,
            selectedRows: tmpRows,
            hasOperat: true
        });
    }
    onChangeRowKey = (selectedRowKeys, selectedRows) => {
        const {details, size} = this.state;
        const tmp = details.map(d => {
            const index = selectedRows.findIndex(v => v.id === d.id && v.dealStatus === partBackOrderDealStatus.未处理);
            if(index !== -1) {
                if(size === partBackOrderDealStatus.申请取消)
                    return Object.assign({}, d, {
                        cancelQuantity: d.cancelQuantity,
                        waitQuantity: d.missQuantity - d.stockAmount - d.cancelQuantity,
                        transforQuantity: 0,
                        dealStatus: size
                    });
                if(size === partBackOrderDealStatus.继续等待)
                    return Object.assign({}, d, {
                        cancelQuantity: 0,
                        waitQuantity: d.missQuantity - d.stockAmount,
                        transforQuantity: 0,
                        dealStatus: size
                    });
                if(size === partBackOrderDealStatus.转新订单)
                    return Object.assign({}, d, {
                        cancelQuantity: 0,
                        waitQuantity: 0,
                        transforQuantity: d.missQuantity - d.stockAmount,
                        dealStatus: size
                    });
            }
            const indexNull = selectedRows.findIndex(v => v.id === d.id);
            if(indexNull === -1)
                return Object.assign({}, d, {
                    cancelQuantity: 0,
                    waitQuantity: 0,
                    transforQuantity: 0,
                    dealStatus: partBackOrderDealStatus.未处理
                });
            return Object.assign({}, d, {
                cancelQuantity: d.dealStatus === partBackOrderDealStatus.未处理 ? 0 : d.cancelQuantity,
                waitQuantity: d.dealStatus === partBackOrderDealStatus.未处理 ? 0 : d.waitQuantity,
                transforQuantity: d.dealStatus === partBackOrderDealStatus.未处理 ? 0 : d.transforQuantity,
            });
        });
        const tmpRows = selectedRows.map(d => {
            if((d.dealStatus !== partBackOrderDealStatus.申请取消 &&
                        d.dealStatus !== partBackOrderDealStatus.继续等待 &&
                        d.dealStatus !== partBackOrderDealStatus.转新订单))
                return Object.assign({}, d, {
                    dealStatus: size
                });
            return d;
        });
        this.setState({
            details: tmp,
            hasOperat: true,
            selectedRowKeys,
            selectedRows: tmpRows
        });
    }
    render() {
        const {formatMessage} = this.props.intl;
        const {details, loading, dealerId, dealerCode, dealerName, size, selectedRows} = this.state;
        const submitable = !hasPermissions(PERMISSION.delivery, this.props.permissions) && details.length > 0;
        const dealerInfo = this.state.dealerId ? {
            id: dealerId,
            code: dealerCode,
            name: dealerName
        } : null;
        const operations = [];
        operations.push(<Radio.Button key="cancel" value={partBackOrderDealStatus.申请取消}>{this.props.intl.formatMessage({
            id: 'confirmorPanel.operation.cancel',
            defaultMessage: '申请取消'
        })}</Radio.Button>);
        operations.push(<Radio.Button key="transfor" value={partBackOrderDealStatus.转新订单}>{this.props.intl.formatMessage({
            id: 'confirmorPanel.operation.transfor',
            defaultMessage: '转新订单'
        })}</Radio.Button>);
        operations.push(<Radio.Button key="wait" value={partBackOrderDealStatus.继续等待}>{this.props.intl.formatMessage({
            id: 'confirmorPanel.operation.wait',
            defaultMessage: '继续等待'
        })}</Radio.Button>);
        const colums = [{
            title: this.props.intl.formatMessage({
                id: 'confirmorPanel.column.brandCode',
                defaultMessage: '品牌'
            }),
            dataIndex: 'brandCode',
            render: (text, record) => (record.brandCode) + record.brandName
        }, {
            title: this.props.intl.formatMessage({
                id: 'confirmorPanel.column.code',
                defaultMessage: '编号'
            }),
            dataIndex: 'code'
        }, {
            title: this.props.intl.formatMessage({
                id: 'confirmorPanel.column.saleOrderCode',
                defaultMessage: '订单编号'
            }),
            dataIndex: 'saleOrderCode'
        }, {
            title: this.props.intl.formatMessage({
                id: 'confirmorPanel.column.saleOrderTypeName',
                defaultMessage: '订单类型'
            }),
            dataIndex: 'saleOrderTypeName'
        }, {
            title: this.props.intl.formatMessage({
                id: 'confirmorPanel.column.orderAmount',
                defaultMessage: 'PI金额'
            }),
            dataIndex: 'orderAmount',
            render: text => formatAmount(text)
        }, {
            title: this.props.intl.formatMessage({
                id: 'confirmorPanel.column.currency',
                defaultMessage: '币种'
            }),
            dataIndex: 'currency',
            render: text => conventEnumValueToString(currency, text)
        }, {
            title: this.props.intl.formatMessage({
                id: 'confirmorPanel.column.orderDate',
                defaultMessage: '提报日期'
            }),
            dataIndex: 'orderDate',
            render: text => formatDateTime(text, DATE_FORMAT)
        }, {
            title: this.props.intl.formatMessage({
                id: 'confirmorPanel.column.status',
                defaultMessage: '缺货单状态'
            }),
            dataIndex: 'status',
            render: text => conventEnumValueToString(partBackOrderStatus, text)
        }, {
            title: formatMessage({
                id: 'confirmorPanel.column.partCode',
                defaultMessage: '备件编号'
            }),
            dataIndex: 'partCode',
        }, {
            title: formatMessage({
                id: 'confirmorPanel.column.partName',
                defaultMessage: '备件名称'
            }),
            dataIndex: 'partName',
        }, {
            title: formatMessage({
                id: 'confirmorPanel.column.orderQuantity',
                defaultMessage: '订购数量'
            }),
            dataIndex: 'orderQuantity'
        }, {
            title: formatMessage({
                id: 'confirmorPanel.column.invoiceAmount',
                defaultMessage: '发票数量'
            }),
            dataIndex: 'invoiceAmount'
        }, {
            title: formatMessage({
                id: 'confirmorPanel.column.invoiceCode',
                defaultMessage: '发票号'
            }),
            dataIndex: 'invoiceCode'
        }, {
            title: formatMessage({
                id: 'confirmorPanel.column.nowMissAmount',
                defaultMessage: '当前缺件数量'
            }),
            dataIndex: 'nowMissAmount'
        }, {
            title: formatMessage({
                id: 'confirmorPanel.column.stockAmount',
                defaultMessage: '已备货数量'
            }),
            dataIndex: 'stockAmount'
        }, {
            title: formatMessage({
                id: 'confirmorPanel.column.notStockQuantity',
                defaultMessage: '未备货数量'
            }),
            dataIndex: 'notStockQuantity'
        }, {
            title: formatMessage({
                id: 'confirmorPanel.column.cancelQuantity',
                defaultMessage: '取消数量'
            }),
            dataIndex: 'cancelQuantity',
            width: 100,
            render: (text, record) => {
                const index = selectedRows.findIndex(v => v.id === record.id && v.dealStatus === partBackOrderDealStatus.申请取消);
                if(this.props.page === 'confirmor')
                    return (<LocalizeInputNumber
                        min={0}
                        max={record.missQuantity - record.stockAmount}
                        disabled={!(size === partBackOrderDealStatus.申请取消) || Boolean(index === -1)}
                        id={record.id}
                        precision={2}
                        value={text} onBlur={this.onUpdateQuantity}/>);
                return text;
            }
        }, {
            title: formatMessage({
                id: 'confirmorPanel.column.transforQuantity',
                defaultMessage: '转订单数量'
            }),
            dataIndex: 'transforQuantity'
        }, {
            title: formatMessage({
                id: 'confirmorPanel.column.waitQuantity',
                defaultMessage: '等待数量'
            }),
            dataIndex: 'waitQuantity'
        }, {
            title: formatMessage({
                id: 'confirmorPanel.column.dealStatus',
                defaultMessage: '处理状态'
            }),
            dataIndex: 'dealStatus',
            render: text => conventEnumValueToString(partBackOrderDealStatus, text)
        }, {
            title: formatMessage({
                id: 'confirmorPanel.column.expectedArrivalDate',
                defaultMessage: '预计到货日期'
            }),
            dataIndex: 'expectedArrivalDate'
        }, {
            title: formatMessage({
                id: 'confirmorPanel.column.replacePartRemark',
                defaultMessage: '替换信息备注'
            }),
            dataIndex: 'replacePartRemark'
        }];
        if(!this.props.isDealerUser)
            colums.splice(2, 0, ...[
                {
                    title: this.props.intl.formatMessage({
                        id: 'confirmorPanel.column.dealerCode',
                        defaultMessage: '总代ERP号'
                    }),
                    dataIndex: 'dealerCode',
                    sorter: true,
                    sortOrder: this.props.sortedColumnKey === 'dealerCode' && this.props.sortedOrder,
                }, {
                    title: this.props.intl.formatMessage({
                        id: 'confirmorPanel.column.dealerName',
                        defaultMessage: '总代名称'
                    }),
                    dataIndex: 'dealerName'
                }
            ]);
        const rowSelection = {
            fixed: true,
            selectedRowKeys: this.state.selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => this.onChangeRowKey(selectedRowKeys, selectedRows),
            getCheckboxProps: record => ({
                disabled: size ? !(record.dealStatus === partBackOrderDealStatus.未处理 || record.dealStatus === size) : true
            })
        };
        return (
            <div className="form-standard">
                <Spin spinning={this.state.loading}>
                    <Card>
                        <Row className="form-standard">
                            {!this.props.isDealerUser &&
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'confirmorPanel.form.dealerId',
                                            defaultMessage: '总代ERP号'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {this.props.id ? <TextInput
                                            disabled={Boolean(this.props.id)}
                                            name="dealerId"
                                            value={`(${dealerCode})${dealerName}`}/> : <DealerSelectPanel
                                            disabled={Boolean(this.props.id)}
                                            value={dealerInfo}
                                            onSelect={this.onSelectDealer} />
                                        }
                                    </FormItem>
                                </Col>
                            }
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem
                                    label={this.props.intl.formatMessage({
                                        id: 'confirmorPanel.form.brandId',
                                        defaultMessage: '品牌'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                    <WrappedSelect
                                        allowClear
                                        disabled={Boolean(this.props.id)}
                                        name="brandId"
                                        value={this.state.brandId}
                                        options={this.props.initEnum.brands}
                                        onChange={this.onChange} />
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem
                                    label={this.props.intl.formatMessage({
                                        id: 'confirmorPanel.form.partOrderCode',
                                        defaultMessage: '订单编号'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                    <TextArea
                                        disabled={Boolean(this.props.id)}
                                        name="partOrderCode"
                                        placeholder={this.props.intl.formatMessage({
                                            id: 'confirmorPanel.form.partOrderCode.placeholder',
                                            defaultMessage: '最多输入1000个订单编号，以回车隔开'
                                        })}
                                        value={this.state.partOrderCode}
                                        onBlur={this.onChange} />
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem
                                    label={this.props.intl.formatMessage({
                                        id: 'confirmorPanel.form.status',
                                        defaultMessage: '缺货单状态'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                    <WrappedSelect
                                        allowClear
                                        disabled={true}
                                        name="status"
                                        value={this.state.status}
                                        options={partBackOrderStatusList}
                                        onChange={this.onChange} />
                                </FormItem>
                            </Col>
                            <Col {...FORM_OPTIONS.col}>
                                <FormItem
                                    label={this.props.intl.formatMessage({
                                        id: 'confirmorPanel.form.dealStatus',
                                        defaultMessage: '处理状态'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                    <WrappedSelect
                                        allowClear
                                        disabled={true}
                                        name="dealStatus"
                                        value={this.state.dealStatus}
                                        options={partBackOrderDealStatusList}
                                        onChange={this.onChange} />
                                </FormItem>
                            </Col>
                        </Row>
                        <Row>
                            <Col span={6} className={styles['inline-button']}>
                                <Button
                                    type="primary"
                                    loading={loading}
                                    onClick={this.onClickSearchBtn}>
                                    {formatMessage({
                                        id: 'confirmorPanel.btn.query',
                                        defaultMessage: '查询'
                                    })}
                                </Button>
                                <Button key="clear" onClick={this.onClickReset}>{formatMessage({
                                    id: 'confirmorPanel.btn.reset',
                                    defaultMessage: '重置'
                                })}</Button>
                            </Col>
                            <Col span={18} className="col-align-right">
                                <Radio.Group value={size} onChange={this.onChangeSize}>
                                    {this.props.page === 'confirmor' && operations}
                                </Radio.Group>
                            </Col>
                        </Row>
                    </Card>
                    <Card
                        title={formatMessage({
                            id: 'confirmorPanel.operation.detail',
                            defaultMessage: '清单信息'
                        })}>
                        {
                            this.props.page === 'confirmor' ? <Table
                                className="white-space-nowrap"
                                columns={colums}
                                rowKey="id"
                                pagination={false}
                                dataSource={details}
                                rowSelection={rowSelection}
                                {...TABLE} /> : <Table
                                className="white-space-nowrap"
                                columns={colums}
                                rowKey="id"
                                pagination={false}
                                dataSource={details}
                                {...TABLE} />
                        }
                    </Card>
                    <Card className={styles.optionBtn}>
                        <Button
                            type="primary"
                            onClick={this.props.page === 'confirmor' ? this.onSubmit : this.onCloseSubmit}
                            disabled={!submitable}
                            loading={loading}>
                            {formatMessage({
                                id: 'confirmorPanel.operation.save',
                                defaultMessage: '保存'
                            })}
                        </Button>
                    </Card>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        onConfirm={this.onClickOkOnPopconfirm}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

ConfirmorPanel.propTypes = {
    initEnum: PropTypes.object.isRequired,
    permissions: PropTypes.array.isRequired,
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    onCloseSubmit: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    history: PropTypes.object,
    id: PropTypes.string,
    intl: PropTypes.object,
    isDealerUser: PropTypes.bool,
    page: PropTypes.string
};

import {connect} from 'react-redux';
import {
    tableSearch,
    onConfirmor,
    onCloseSubmit
} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {createSelector} from 'reselect';

const getInitData = createSelector(
    state => state.getIn(['page', 'domainData', 'initData']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? initData.brands.map(item => ({
            text: `${'('}${item.code}${')'}${item.name}`,
            value: item.id
        })) : [];
        return {
            brands
        };
    }
);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = (state, props) => ({
    permissions: getPermissions(state),
    isDealerUser: state.getIn((['page', 'domainData', 'initData', 'isDealerUser'])),
    initEnum: getInitData(state),
});
const mapDispatchToProps = (dispatch, props) => ({
    onSubmit: details => dispatch(onConfirmor(details)),
    onCloseSubmit: data => dispatch(onCloseSubmit(data)),
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(ConfirmorPanel));
